#include<iostream>

#include<stdio.h>

#include <pthread.h>

#include<vector>

#include<unistd.h>

#include<errno.h>

#include<string.h>

using namespace std;

struct task
{
    string _name;
    pthread_t _PT;
    pthread_mutex_t* _mx;
};

class mutex_guard //使用全局锁封装
{
public:
    mutex_guard()
    {
        pthread_mutex_lock(&_mx);
    }

    ~mutex_guard()
    {
        pthread_mutex_unlock(&_mx);
    }
private:
    static pthread_mutex_t _mx;
};
pthread_mutex_t mutex_guard:: _mx = PTHREAD_MUTEX_INITIALIZER;

int num = 1000;

void* my_pthread(void* arg)
{
    task* tk = static_cast<task*>(arg);
    while(1)
    {
        {        
            mutex_guard tmp;
            if(num > 0)
            {
                printf("%s抢到一张票：%d\n", (tk->_name).c_str(), num);
                num--;
            }
            else
            {
                break;
            }
        }
        usleep(1000);
    }
    return nullptr;
}

int main()
{
    vector<task*>arr;
    for(int i = 0; i < 10; ++i)
    {
        task* tmp = new task;
        tmp->_name = "thread";
        tmp->_name += i + '0';
        pthread_create(&(tmp->_PT), nullptr, my_pthread, tmp);
        arr.push_back(tmp);
    }

    for(auto& e : arr)
    {
        pthread_join(e->_PT, nullptr);
    }

    for(auto& e : arr)
    {
        delete e;
    }

    return 0;
}